#coding=utf-8
from uliweb import expose

#可以省略直接引用
from uliweb import request, error, redirect, Response
from uliweb.orm import get_model,do_,Begin,Commit,Rollback
import random
from sqlalchemy import desc,and_,or_
from sqlalchemy.sql import select

def __begin__():
    """
    用户验证 权限验证
    """
    from uliweb import functions
    functions.require_login()
    return functions.has_role()

@expose('/devices')
class Devices(object):

    #def __begin__(self):
        #"""
        #用户验证
        #"""
        #from uliweb import functions
        #return functions.require_login()

    def __init__(self):
        from uliweb.orm import get_model
        self.hardwarestatusmodel = get_model('hardwarestatus')
        self.hardwaremodel = get_model('hardware')
        self.hardwaretypemodel = get_model('hardwaretype')
        self.hardwarewarrantymodel = get_model('hardwarewarranty')
        self.servermodel = get_model('server')
        self.switchmodel = get_model('switch')
        self.switchipmodel = get_model('switchip')
        self.switchportmodel = get_model('switchport')
        self.servercpumodel = get_model('servercpu')
        self.servermemmodel = get_model('servermem')
        self.serverdiskmodel = get_model('serverdisk')
        self.serverpowermodel = get_model('serverpower')
        self.serverethmodel = get_model('serverethernet')
        self.serverethipmodel = get_model('serverethernetip')
        self.ipaddrmodel = get_model('ipaddress')
        self.rackspacemodel = get_model('rackspace')
        self.computerroommodel = get_model('computerroom')
        self.osmodel = get_model('operatingsystem')
        self.serversystemmodel = get_model('serversystem')
        self.opersgroupprojectmodel = get_model('opersgroupproject')
        self.hardwaremanufacturermodel = get_model('hardwaremanufacturer')

    def _get_hardwarestatus(self, id):
        _data = self.hardwarestatusmodel.get(int(id))
        if not _data:
            error('没找到这条记录')
        return _data
    
    def _get_hardware(self, id):
        _data = self.hardwaremodel.get(int(id))
        if not _data:
            error('没找到这条记录')
        return _data
    
    def _get_hardwarewarranty(self, id):
        _data = self.hardwarewarrantymodel.get(int(id))
        if not _data:
            error('没找到这条记录')
        return _data

    def _get_hardwaretype(self, id):
        _data = self.hardwaretypemodel.get(int(id))
        if not _data:
            error('没找到这条记录')
        return _data

    def _get_server(self, id):
        _data = self.servermodel.get(int(id))
        if not _data:
            error('没找到这条记录')
        return _data    

    def _get_switch(self, id):
        _data = self.switchmodel.get(int(id))
        if not _data:
            error('没找到这条记录')
        return _data

    def hardwarestatus(self):
        """
        硬件状态信息
        """
        return {}    

    def hardwarestatusadd(self):
        """
        添加硬件状态信息
        """
        return {}

    def hardwarestatusedit(self):
        """
        编辑硬件状态信息
        """
        _id = request.GET.get("id")
        if _id == "":
            return {'hardwarestatus_type':''}
        else:
            ormdata = functions.get_object(self.hardwarestatusmodel, _id, cache=True)
    
            if ormdata.hardwarestatus_type == '':
                return {'hardwarestatus_type':0}
            else:
                return {'hardwarestatus_type':ormdata.hardwarestatus_type}        

    def hardwarestatussave(self):
        """
        保存硬件状态信息
        """
        ##得到所有的参数
        #all = request.POST

        #for k,v in all.iteritems():
            #print k,v
        _id = request.POST.get('id')
        hardwarestatus_name= request.POST.get('hardwarestatus_name')
        hardwarestatus_type= request.POST.get('hardwarestatus_type')
        comment = request.POST.get('comment')

        if _id == None:
            ormdata = self.hardwarestatusmodel(hardwarestatus_name=hardwarestatus_name,
                                               hardwarestatus_type=hardwarestatus_type,
                                               comment=comment
                                               )
        else:
            ormdata = self._get_hardwarestatus(_id)
            #ormdata = functions.get_object(self.hardwarestatusmodel, id, cache=True)

            ormdata.hardwarestatus_name=hardwarestatus_name
            ormdata.hardwarestatus_type=hardwarestatus_type
            ormdata.comment=comment

        try:
            ormdata.save()

            return json({"success":200,"msg":"添加成功"})
        except:
            return json({"error":500,"msg":"硬件状态已经存在"})

    def hardwarestatusdel(self):
        """
        删除硬件状态信息
        """
        _id = request.POST.get('id')

        mid = []
        for i in _id.split(','):
            mid.append(int(i))

        #一次删除多个
        self.hardwarestatusmodel.filter(self.hardwarestatusmodel.c.id.in_(mid)).remove()

        d = {"status":"200","msg":"删除成功"}
        return json(d)

    def hardwaretype(self):
        """
        硬件类型
        """
        return {}    

    def hardwaretypeadd(self):
        """
        添加硬件类型
        """
        return {}

    def hardwaretypeedit(self):
        """
        编辑硬件类型
        """
        _id = request.GET.get("id")
        
        if _id == "":
            data = {'hardware_isport':''}
        else:
            ormdata = self._get_hardwaretype(_id)
    
            data = {'hardware_isport':ormdata.hardware_isport
                    }        

        return data

    def hardwaretypesave(self):
        """
        保存硬件类型
        """
        _id = request.POST.get('id')
        hardwaretype_name= request.POST.get('hardwaretype_name') 
        hardware_isport= request.POST.get('hardware_isport')
        comment = request.POST.get('comment')

        if _id == None:
            ormdata = self.hardwaretypemodel(hardwaretype_name=hardwaretype_name,
                                             hardware_isport=hardware_isport,
                                             comment=comment
                                             )
        else:
            ormdata = self._get_hardwaretype(_id)

            ormdata.hardwaretype_name=hardwaretype_name
            ormdata.hardware_isport=hardware_isport

            ormdata.comment=comment

        try:
            ormdata.save()

            return json({"success":200,"msg":"添加成功"})
        except:
            return json({"error":500,"msg":"硬件类型已经存在"})

    def hardwaretypedel(self):
        """
        删除硬件类型
        """
        _id = request.POST.get('id')

        mid = []
        for i in _id.split(','):
            mid.append(int(i))

        #一次删除多个
        self.hardwaretypemodel.filter(self.hardwaretypemodel.c.id.in_(mid)).remove()

        d = {"status":"200","msg":"删除成功"}
        return json(d)    

    def hardwarewarranty(self):
        """
        硬件保修状态信息
        """
        return {}    

    def hardwarewarrantyadd(self):
        """
        添加硬件保修状态信息
        """
        return {}

    def hardwarewarrantyedit(self):
        """
        编辑硬件保修状态信息
        """
        _id = request.GET.get("id")
        return {}        

    def hardwarewarrantysave(self):
        """
        保存硬件状态信息
        """
        ##得到所有的参数
        #all = request.POST

        #for k,v in all.iteritems():
            #print k,v
        _id = request.POST.get('id')
        hardwarewarranty_name= request.POST.get('hardwarewarranty_name')
        comment = request.POST.get('comment')

        if _id == None:
            ormdata = self.hardwarewarrantymodel(hardwarewarranty_name=hardwarewarranty_name,
                                               comment=comment
                                               )
        else:
            ormdata = self._get_hardwarewarranty(_id)
            ormdata.hardwarewarranty_name=hardwarewarranty_name
            ormdata.comment=comment

        try:
            ormdata.save()

            return json({"success":200,"msg":"添加成功"})
        except:
            return json({"error":500,"msg":"硬件保修状态已经存在"})

    def hardwarewarrantydel(self):
        """
        删除硬件保修状态信息
        """
        _id = request.POST.get('id')

        mid = []
        for i in _id.split(','):
            mid.append(int(i))

        #一次删除多个
        self.hardwarewarrantymodel.filter(self.hardwarewarrantymodel.c.id.in_(mid)).remove()

        d = {"status":"200","msg":"删除成功"}
        return json(d)

    def hardwaremanufacturer(self):
        """
        硬件品牌信息
        """
        return {}    

    def hardwaremanufactureradd(self):
        """
        添加硬件品牌信息
        """
        return {}

    def hardwaremanufactureredit(self):
        """
        编辑硬件品牌信息
        """
        _id = request.GET.get("id")
        return {}        

    def hardwaremanufacturersave(self):
        """
        保存硬件品牌信息
        """

        _id = request.POST.get('id')
        hardwaremanufacturer_name= request.POST.get('hardwaremanufacturer_name')

        if _id == None:
            ormdata = self.hardwaremanufacturermodel(hardwaremanufacturer_name=hardwaremanufacturer_name
                                               )
        else:
            ormdata = functions.get_object(self.hardwaremanufacturermodel, _id, cache=True, use_local=True)
            ormdata.hardwaremanufacturer_name=hardwaremanufacturer_name

        try:
            ormdata.save()

            return json({"success":200,"msg":"添加成功"})
        except:
            return json({"error":500,"msg":"硬件品牌信息已经存在"})

    def hardwaremanufacturerdel(self):
        """
        删除硬件品牌信息
        """
        _id = request.POST.get('id')

        mid = []
        for i in _id.split(','):
            mid.append(int(i))

        #一次删除多个
        self.hardwaremanufacturermodel.filter(self.hardwaremanufacturermodel.c.id.in_(mid)).remove()

        d = {"status":"200","msg":"删除成功"}
        return json(d)


    def hardware(self):
        """
        品牌设备
        """
        return {}    

    def hardwareadd(self):
        """
        添加品牌设备
        """
        return {}

    def hardwareedit(self):
        """
        编辑品牌设备
        """
        _id = request.GET.get("id")
        
        #ormdata = self._get_hardware(_id)
        ormdata = functions.get_object(self.hardwaremodel, _id, cache=True, use_local=True)

        data = {'hardwaretype_id':ormdata.hardwaretype_id.id,
                'hardware_isport':ormdata.hardwaretype_id.hardware_isport,
                'hardwaremanufacturer_name':ormdata.hardwaremanufacturer_id
                }

        return data

    def hardwaresave(self):
        """
        保存品牌设备
        """
        _id = request.POST.get('id')
        hardware_manufacturer= request.POST.get('hardware_manufacturer')
        hardware_name= request.POST.get('hardware_name')
        hardwaretype_id= request.POST.get('hardwaretype_id') 
        hardware_port_num= request.POST.get('hardware_port_num')
        comment = request.POST.get('comment')

        if hardware_port_num == '':
            hardware_port_num = 0  

        if _id == None:

            ormdata = self.hardwaremodel(hardwaremanufacturer_id=hardware_manufacturer,
                                         hardware_name=hardware_name,
                                         hardwaretype_id=hardwaretype_id,
                                         hardware_port_num=hardware_port_num,
                                         comment=comment
                                         )
        else:
            #ormdata = self._get_hardware(_id)

            ormdata = functions.get_object(self.hardwaremodel, _id, cache=True, use_local=True)
            
            ormdata.hardwaremanufacturer_id=hardware_manufacturer
            ormdata.hardware_name=hardware_name
            ormdata.hardwaretype_id=hardwaretype_id
            ormdata.hardware_port_num=hardware_port_num
            ormdata.comment=comment

        try:
            ormdata.save()

            return json({"success":200,"msg":"添加成功"})
        except:
            return json({"error":500,"msg":"品牌设备已经存在"})

    def hardwaredel(self):
        """
        删除品牌设备
        """
        _id = request.POST.get('id')

        mid = []
        for i in _id.split(','):
            mid.append(int(i))

        #一次删除多个
        self.hardwaremodel.filter(self.hardwaremodel.c.id.in_(mid)).remove()

        d = {"status":"200","msg":"删除成功"}
        return json(d)      

    def server(self):
        """
        服务器硬件信息
        """
        return {} 

    def serveradd(self):
        """
        服务器硬件信息
        """
        return {} 

    def serveredit(self):
        """
        服务器硬件信息
        """
        _id = request.GET.get("id")
        
        if _id == "":
            return {}
        
        #ormdata = self._get_server(_id)
        ormdata = functions.get_object(self.servermodel, _id, cache=True, use_local=True)
        
        ormdata_system = functions.get_object(self.serversystemmodel, _id, cache=True, use_local=True)

        if ormdata_system.department_id == None:
            department_id = ''
        else:
            department_id = ormdata_system.department_id
            
        if ormdata_system.opersgroup_id == None:
            opersgroup_id = ''
        else:
            opersgroup_id = ormdata_system.opersgroup_id

        if ormdata_system.opersgroupproject_id == None:
            opersgroupproject_id = ''
        else:
            opersgroupproject_id = ormdata_system.opersgroupproject_id
            
        if ormdata_system.applicationtype_id == None:
            applicationtype_id = ''
        else:
            applicationtype_id = ormdata_system.applicationtype_id


        cpu = ormdata.cpu.all()
        cpu_num = ormdata.cpu.count()
        mem = ormdata.mem.all()
        mem_num = ormdata.mem.count()
        disk = ormdata.disk.all()
        disk_num = ormdata.disk.count()
        power = ormdata.power.all()
        power_num = ormdata.power.count()
        eth = ormdata.eth.all()
        eth_num = ormdata.eth.count()
        eth_ip = ormdata.eth_ip.all()
        eth_ip_num = ormdata.eth_ip.count()

        data = {'hardwarestatus_id':ormdata.hardwarestatus_id.id,
                'applicationtype_id':applicationtype_id,
                'computerroom_id':ormdata.rackspace_id.computerroom_id.id,
                'rackspace_id':ormdata.rackspace_id.id,
                'hardware_manufacturer':ormdata.hardware_id.hardwaremanufacturer_id,
                'hardware_id':ormdata.hardware_id.id,
                'server_cdrom':ormdata.server_cdrom,
                'hardwarewarranty_id':ormdata.hardwarewarranty_id,
                'server_sn':ormdata.server_sn,
                'server_asset_tag':ormdata.server_asset_tag,
                'server_height':ormdata.server_height,
                'server_raidtype':ormdata.server_raidtype,
                'server_warranty_datetime':ormdata.server_warranty_datetime,
                'server_price':ormdata.server_price,
                'server_purchasing_director':ormdata.server_purchasing_director,
                'server_buy_datetime':ormdata.server_buy_datetime,
                'department_id':department_id,
                'opersgroup_id':opersgroup_id,
                'opersgroupproject_id':opersgroupproject_id,
                'os_id':ormdata_system.os_id,
                'system_raid':ormdata_system.system_raid,
                'system_partition':ormdata_system.system_partition,
                'system_hostname':ormdata_system.system_hostname,
                'cpu':cpu,
                'cpu_num':cpu_num,
                'mem':mem,
                'mem_num':mem_num,      
                'disk':disk,
                'disk_num':disk_num,  
                'power':power,
                'power_num':power_num,  
                'eth':eth,
                'eth_num':eth_num
                }        

        #获取网卡配置信息
        n = 1
        for i in eth_ip:
            data["ethernet_type"+str(n)]=i.ethernet_type
            data["ethernet_physical_interface"+str(n)]=i.ethernet_physical_interface
            data["ethernet_dev_name"+str(n)]=i.ethernet_dev_name
            data["ethernet_mac"+str(n)]=i.ethernet_mac
            data["ethernet_ip"+str(n)]=i.ethernet_ip
            data["ethernet_mip"+str(n)]=i.ethernet_mip
            if i.switch_id == None:
                data["switch_id"+str(n)]=''
            else:
                data["switch_id"+str(n)]=i.switch_id
            if i.switchport_id_port == 0:
                data["switchport_id_port"+str(n)]=''
            else:
                data["switchport_id_port"+str(n)]=i.switchport_id_port
            n = n + 1

        for i in range(n,6):

            data["ethernet_type"+str(i)]=''
            data["ethernet_physical_interface"+str(i)]=''
            data["ethernet_dev_name"+str(i)]=''
            data["ethernet_mac"+str(i)]=''
            data["ethernet_ip"+str(i)]=''
            data["ethernet_mip"+str(i)]=''
            data["switch_id"+str(i)]=''
            data["switchport_id_port"+str(i)]=''

        return data


    def serversave(self):
        """
        保存服务器硬件信息
        """
        _id = request.POST.get('id')
        #server_oid= request.POST.get('server_oid')
        #computerroom_id= request.POST.get('computerroom_id')
        rackspace_id= request.POST.get('rackspace_id')
        hardware_id= request.POST.get('hardware_name')
        server_sn= request.POST.get('server_sn')
        server_cpu= request.POST.getlist('server_cpu')
        server_mem= request.POST.getlist('server_mem')
        server_disk= request.POST.getlist('server_disk')
        server_power= request.POST.getlist('server_power')
        server_ethernet= request.POST.getlist('server_ethernet')
        server_height= request.POST.get('server_height')
        server_asset_tag= request.POST.get('server_asset_tag')
        #有无CDROM
        server_cdrom= request.POST.get('server_cdrom')
        #采购价格
        server_price= request.POST.get('server_price')
        #采购负责人
        server_purchasing_director= request.POST.get('server_purchasing_director')
        #采购日期
        server_buy_datetime= request.POST.get('server_buy_datetime')
        #RAID型号
        server_raidtype= request.POST.get('server_raidtype')
        #是否过保
        hardwarewarranty_id= request.POST.get('hardwarewarranty_id')
        #过保日期
        server_warranty_datetime= request.POST.get('server_warranty_datetime')
        hardwarestatus_id= request.POST.get('hardwarestatus_id')
        comment = request.POST.get('comment')
        
        #系统属性表
        os_id= request.POST.get('os_id')
        system_raid= request.POST.get('system_raid')
        system_partition= request.POST.get('system_partition')
        system_hostname= request.POST.get('system_hostname')
        department_id= request.POST.get('department_id')
        opersgroup_id= request.POST.get('opersgroup_id')
        opersgroupproject_id= request.POST.get('opersgroupproject_id')
        applicationtype_id= request.POST.get('applicationtype_id')
        
        #整形字段，不能保存空值
        if department_id == "":
            department_id = None
        if opersgroup_id == "":
            opersgroup_id = None        
        if opersgroupproject_id == "":
            opersgroupproject_id = None
        if applicationtype_id == "":
            applicationtype_id = None

        #网络接口信息
        ethernet_type1 = request.POST.get('ethernet_type1')
        ethernet_physical_interface1 = request.POST.get('ethernet_physical_interface1')
        ethernet_dev_name1 = request.POST.get('ethernet_dev_name1')
        ethernet_mac1 = request.POST.get('ethernet_mac1')
        ethernet_ip1 = request.POST.get('ethernet_ip1')
        ethernet_mip1 = request.POST.get('ethernet_mip1')
        switch_id1 = request.POST.get('switch_id1')
        switchport_id_port1 = request.POST.get('switchport_id_port1')

        ethernet_type2 = request.POST.get('ethernet_type2')
        ethernet_physical_interface2 = request.POST.get('ethernet_physical_interface2')
        ethernet_dev_name2 = request.POST.get('ethernet_dev_name2')
        ethernet_mac2 = request.POST.get('ethernet_mac2')
        ethernet_ip2 = request.POST.get('ethernet_ip2')
        ethernet_mip2 = request.POST.get('ethernet_mip2')
        switch_id2 = request.POST.get('switch_id2')
        switchport_id_port2 = request.POST.get('switchport_id_port2')        

        ethernet_type3 = request.POST.get('ethernet_type3')
        ethernet_physical_interface3 = request.POST.get('ethernet_physical_interface3')
        ethernet_dev_name3 = request.POST.get('ethernet_dev_name3')
        ethernet_mac3 = request.POST.get('ethernet_mac3')
        ethernet_ip3 = request.POST.get('ethernet_ip3')
        ethernet_mip3 = request.POST.get('ethernet_mip3')
        switch_id3 = request.POST.get('switch_id3')
        switchport_id_port3 = request.POST.get('switchport_id_port3') 

        ethernet_type4 = request.POST.get('ethernet_type4')
        ethernet_physical_interface4 = request.POST.get('ethernet_physical_interface4')
        ethernet_dev_name4 = request.POST.get('ethernet_dev_name4')
        ethernet_mac4 = request.POST.get('ethernet_mac4')
        ethernet_ip4 = request.POST.get('ethernet_ip4')
        ethernet_mip4 = request.POST.get('ethernet_mip4')
        switch_id4 = request.POST.get('switch_id4')
        switchport_id_port4 = request.POST.get('switchport_id_port4')         

        ethernet_type5 = request.POST.get('ethernet_type5')
        ethernet_physical_interface5 = request.POST.get('ethernet_physical_interface5')
        ethernet_dev_name5 = request.POST.get('ethernet_dev_name5')
        ethernet_mac5 = request.POST.get('ethernet_mac5')
        ethernet_ip5 = request.POST.get('ethernet_ip5')
        ethernet_mip5 = request.POST.get('ethernet_mip5')
        switch_id5 = request.POST.get('switch_id5')
        switchport_id_port5 = request.POST.get('switchport_id_port5')          

        if ethernet_ip1 != '' and ethernet_type1 == '':
            return json({"error":500,"msg":"错误:网卡接入配置1 配置IP，但是没有配置接口类型"})

        if ethernet_ip2 != '' and ethernet_type2 == '':
            return json({"error":500,"msg":"错误:网卡接入配置2 配置IP，但是没有配置接口类型"})

        if ethernet_ip3 != '' and ethernet_type3 == '':
            return json({"error":500,"msg":"错误:网卡接入配置3 配置IP，但是没有配置接口类型"})

        if ethernet_ip4 != '' and ethernet_type4 == '':
            return json({"error":500,"msg":"错误:网卡接入配置4 配置IP，但是没有配置接口类型"})

        if ethernet_ip5 != '' and ethernet_type5 == '':
            return json({"error":500,"msg":"错误:网卡接入配置5 配置IP，但是没有配置接口类型"})

        if os_id == None or os_id == "None":
            return json({"error":500,"msg":"错误:操作系统类型不能是None"})

        if _id == None:
            ormdata = self.servermodel(server_cdrom=server_cdrom,
                                       rackspace_id=rackspace_id,
                                       hardware_id=hardware_id,
                                       server_sn=server_sn,
                                       server_price=server_price,
                                       server_purchasing_director=server_purchasing_director,
                                       server_raidtype=server_raidtype,
                                       hardwarewarranty_id=hardwarewarranty_id,
                                       server_warranty_datetime=server_warranty_datetime,
                                       server_buy_datetime=server_buy_datetime,
                                       server_height=server_height,
                                       server_asset_tag=server_asset_tag,
                                       hardwarestatus_id=hardwarestatus_id,
                                       comment=comment
                                       )          
        else:
            #ormdata = self._get_server(_id)

            ormdata = functions.get_object(self.servermodel, _id, cache=True, use_local=True)
            ormdata.server_cdrom=server_cdrom
            ormdata.rackspace_id=rackspace_id
            ormdata.hardware_id=hardware_id
            ormdata.server_sn=server_sn
            ormdata.server_price=server_price
            ormdata.server_purchasing_director=server_purchasing_director
            ormdata.server_raidtype=server_raidtype
            ormdata.hardwarewarranty_id=hardwarewarranty_id
            ormdata.server_warranty_datetime=server_warranty_datetime
            ormdata.server_buy_datetime=server_buy_datetime
            ormdata.server_height=server_height
            ormdata.server_asset_tag=server_asset_tag
            ormdata.hardwarestatus_id=hardwarestatus_id
            ormdata.comment=comment

        Begin()

        try:
            ormdata.save()
            
            #保存系统属性
            if _id == None:
                ormdata_system = self.serversystemmodel(server_id = ormdata,
                                                        os_id = os_id,
                                                        system_raid = system_raid,
                                                        system_partition = system_partition,
                                                        system_hostname = system_hostname,
                                                        department_id = department_id,
                                                        opersgroup_id = opersgroup_id,
                                                        opersgroupproject_id = opersgroupproject_id,
                                                        applicationtype_id = applicationtype_id
                                                        )
            else:
                ormdata_system = functions.get_object(self.serversystemmodel, _id, cache=True, use_local=True)
                ormdata_system.os_id=os_id
                ormdata_system.system_raid=system_raid
                ormdata_system.system_partition=system_partition
                ormdata_system.system_hostname=system_hostname
                ormdata_system.department_id=department_id
                ormdata_system.opersgroup_id=opersgroup_id
                ormdata_system.opersgroupproject_id=opersgroupproject_id
                ormdata_system.applicationtype_id=applicationtype_id
                
            ormdata_system.save()
        
            if _id != None:
                self.servercpumodel.filter(self.servercpumodel.c.server_id == _id).remove()
                self.servermemmodel.filter(self.servermemmodel.c.server_id == _id).remove()
                self.serverdiskmodel.filter(self.serverdiskmodel.c.server_id == _id).remove()
                self.serverpowermodel.filter(self.serverpowermodel.c.server_id == _id).remove()
                self.serverethmodel.filter(self.serverethmodel.c.server_id == _id).remove()
                self.serverethipmodel.filter(self.serverethipmodel.c.server_id == _id).remove()
                #self.serversystemmodel.filter(self.serversystemmodel.c.server_id == _id).remove()
                self.ipaddrmodel.filter(self.ipaddrmodel.c.server_id==_id).update(server_id=None,ip_status=0)

            if server_cpu[0] != '':
                if not self._servercpusave(server_cpu, ormdata):
                    Rollback(close=True)
                    return json({"error":500,"msg":"CPU信息非法,设备添加失败"})

            if server_disk[0] != '':
                if not self._serverdisksave(server_disk, ormdata):
                    Rollback(close=True)
                    return json({"error":500,"msg":"磁盘信息非法,设备添加失败"})

            if server_mem[0] != '':
                if not self._servermemsave(server_mem, ormdata):
                    Rollback(close=True)
                    return json({"error":500,"msg":"内存信息非法,设备添加失败"})

            if server_power[0] != '':
                if not self._serverpowersave(server_power, ormdata):
                    Rollback(close=True)
                    return json({"error":500,"msg":"电源信息非法,设备添加失败"})

            if server_ethernet[0] != '':
                if not self._serverethsave(server_ethernet, ormdata):
                    Rollback(close=True)
                    return json({"error":500,"msg":"网卡信息非法,设备添加失败"})

            if ethernet_ip1 != '':
                if not self._serverethernetipsave(ormdata, ethernet_type1,
                                                 ethernet_physical_interface1,
                                                 ethernet_dev_name1,
                                                 ethernet_mac1,
                                                 ethernet_ip1,
                                                 ethernet_mip1,
                                                 switch_id1,
                                                 switchport_id_port1):
                    Rollback(close=True)
                    return json({"error":500,"msg":"网卡接入配置1错误,IP不存在或者IP已经被使用,设备添加失败"})

            if ethernet_ip2 != '':
                if not self._serverethernetipsave(ormdata, ethernet_type2,
                                                 ethernet_physical_interface2,
                                                 ethernet_dev_name2,
                                                 ethernet_mac2,
                                                 ethernet_ip2,
                                                 ethernet_mip2,
                                                 switch_id2,
                                                 switchport_id_port2):
                    Rollback(close=True)
                    return json({"error":500,"msg":"网卡接入配置2错误,IP不存在或者IP已经被使用,设备添加失败"})

            if ethernet_ip3 != '':
                if not self._serverethernetipsave(ormdata, ethernet_type3,
                                                 ethernet_physical_interface3,
                                                 ethernet_dev_name3,
                                                 ethernet_mac3,
                                                 ethernet_ip3,
                                                 ethernet_mip3,
                                                 switch_id3,
                                                 switchport_id_port3):
                    Rollback(close=True)
                    return json({"error":500,"msg":"网卡接入配置3错误,IP不存在或者IP已经被使用,设备添加失败"})

            if ethernet_ip4 != '':
                if not self._serverethernetipsave(ormdata, ethernet_type4,
                                                 ethernet_physical_interface4,
                                                 ethernet_dev_name4,
                                                 ethernet_mac4,
                                                 ethernet_ip4,
                                                 ethernet_mip4,
                                                 switch_id4,
                                                 switchport_id_port4):
                    Rollback(close=True)
                    return json({"error":500,"msg":"网卡接入配置4错误,IP不存在或者IP已经被使用,设备添加失败"})

            if ethernet_ip5 != '':
                if not self._serverethernetipsave(ormdata, ethernet_type5,
                                                 ethernet_physical_interface5,
                                                 ethernet_dev_name5,
                                                 ethernet_mac5,
                                                 ethernet_ip5,
                                                 ethernet_mip5,
                                                 switch_id5,
                                                 switchport_id_port5):
                    Rollback(close=True)
                    return json({"error":500,"msg":"网卡接入配置5错误,IP不存在或者IP已经被使用,设备添加失败"})

            
            Commit(close=True)
            return json({"success":200,"msg":"添加成功"})
        except Exception,e:
            print e
            Rollback(close=True)
            return json({"error":500,"msg":"设备已经存在"})


    def _serverethsave(self,server_ethernet,server_id):
        """
        保存网卡信息
        """
        if server_ethernet[0] != '':
            for i in server_ethernet:
                (servereth_type,servereth_num) = i.split('*')
                ethernet = self.serverethmodel(servereth_type = servereth_type,
                                               servereth_num = servereth_num,
                                               server_id = server_id
                                               )
                try:
                    ethernet.save()  
                    return True
                except:
                    return False

    def _serverpowersave(self,server_power,server_id):
        """
        保存电源信息
        """
        for i in server_power:
            (serverpower_type,serverpower_kw,serverpower_num) = i.split('*')
            power = self.serverpowermodel(serverpower_type = serverpower_type,
                                          serverpower_kw = serverpower_kw,
                                          serverpower_num = serverpower_num,
                                          server_id = server_id
                                          )
            try:
                power.save()  
                return True
            except:
                return False      

    def _servermemsave(self,server_mem,server_id):
        """
        保存内存信息
        """
        for i in server_mem:
            (servermem_type,servermem_hz,servermem_size,servermem_num) = i.split('*')
            #内存大小默认使用M为单位
            if "G" in servermem_size:
                servermem_size = int(filter(str.isdigit, str(servermem_size))) * 1024
            elif "M" in servermem_size:
                servermem_size = int(filter(str.isdigit, str(servermem_size)))
            else:
                servermem_size = servermem_size
            
            mem = self.servermemmodel(servermem_type = servermem_type,
                                      servermem_hz = servermem_hz,
                                      servermem_size = servermem_size,
                                      servermem_num = servermem_num,
                                      server_id = server_id
                                      )
            try:
                mem.save()  
                return True
            except:
                return False        

    def _serverdisksave(self,server_disk,server_id):
        """
        保存磁盘信息
        """
        for i in server_disk:
            (serverdisk_type,serverdisk_speed,serverdisk_size,serverdisk_num) = i.split('*')
            #磁盘默认使用G为单位
            if "G" in serverdisk_size:
                serverdisk_size = int(filter(str.isdigit, str(serverdisk_size)))
            elif "T" in serverdisk_size:
                serverdisk_size = int(filter(str.isdigit, str(serverdisk_size))) * 1024
            elif "P" in serverdisk_size:
                serverdisk_size = int(filter(str.isdigit, str(serverdisk_size))) * 1024 * 1024            
            else:
                serverdisk_size = serverdisk_size       
                
            disk = self.serverdiskmodel(serverdisk_type = serverdisk_type,
                                        serverdisk_speed = serverdisk_speed,
                                        serverdisk_size = serverdisk_size,
                                        serverdisk_num = serverdisk_num,
                                        server_id = server_id
                                        )
            try:
                disk.save()  
                return True
            except:
                return False                

    def _servercpusave(self,server_cpu,server_id):
        """
        保存cpu信息
        """
        for i in server_cpu:
            (servercpu_type,servercpu_hz,servercpu_num) = i.split('*')
            cpu = self.servercpumodel(servercpu_type = servercpu_type,
                                      servercpu_hz = servercpu_hz,
                                      servercpu_num = servercpu_num,
                                      server_id = server_id
                                      )
            try:
                cpu.save()
                return True
            except:
                return False

    def _serverethernetipsave(self,server_id,ethernet_type,ethernet_physical_interface,
                             ethernet_dev_name,ethernet_mac,ethernet_ip,ethernet_mip,
                             switch_id,switchport_id_port):
        """
        保存设备ip
        """
        if switchport_id_port == '':
            switchport_id_port = None
        if ethernet_physical_interface == '':
            ethernet_physical_interface = None
        if ethernet_type == '':
            ethernet_type = None
        if switch_id == '':
            switch_id = None        

        eth_ip = self.serverethipmodel(server_id = server_id,
                                       ethernet_type = ethernet_type,
                                       ethernet_physical_interface = ethernet_physical_interface,
                                       ethernet_dev_name = ethernet_dev_name,
                                       ethernet_mac = ethernet_mac,
                                       ethernet_ip = ethernet_ip,
                                       ethernet_mip = ethernet_mip,
                                       switch_id = switch_id,
                                       switchport_id_port = switchport_id_port
                                       )
        try:
            eth_ip.save()

            #更新IP地址表
            ip_status = list(self.ipaddrmodel.filter(self.ipaddrmodel.c.ip_address==ethernet_ip).limit(1).values(self.ipaddrmodel.c.ip_status))[0][0]
            if ip_status == 1:
                return False
            else:
                self.ipaddrmodel.filter(self.ipaddrmodel.c.ip_address==ethernet_ip).update(server_id=server_id,ip_status=1)
            return True
        except:
            return False

    def serverdel(self):
        """
        删除服务器
        """
        _id = request.POST.get('id')

        mid = []
        for i in _id.split(','):
            mid.append(int(i))

        #一次删除多个
        self.servermodel.filter(self.servermodel.c.id.in_(mid)).remove()

        self.servercpumodel.filter(self.servercpumodel.c.server_id.in_(mid)).remove()
        self.servermemmodel.filter(self.servermemmodel.c.server_id.in_(mid)).remove()
        self.serverdiskmodel.filter(self.serverdiskmodel.c.server_id.in_(mid)).remove()
        self.serverpowermodel.filter(self.serverpowermodel.c.server_id.in_(mid)).remove()
        self.serverethmodel.filter(self.serverethmodel.c.server_id.in_(mid)).remove()
        self.serverethipmodel.filter(self.serverethipmodel.c.server_id.in_(mid)).remove()
        self.serversystemmodel.filter(self.serversystemmodel.c.server_id.in_(mid)).remove()
        self.ipaddrmodel.filter(self.ipaddrmodel.c.server_id.in_(mid)).update(server_id=None,ip_status=0)

        d = {"status":"200","msg":"删除成功"}
        return json(d)

    def serverdetail(self):
        """
        查看设备明细
        参数：
              id:设备ID
        """
        _id = request.GET.get("id")

        if _id == "":
            return {}
        
        #ormdata = self._get_server(_id)
        
        ormdata = functions.get_object(self.servermodel, _id, cache=True, use_local=True)
        
        ormdata_system = functions.get_object(self.serversystemmodel, _id, cache=True, use_local=True)

        if ormdata_system.department_id == None:
            department_name = ''
        else:
            department_name = ormdata_system.department_id.department_name
            
        if ormdata_system.opersgroup_id == None:
            opersgroup_name = ''
        else:
            opersgroup_name = ormdata_system.opersgroup_id.opersgroup_name

        if ormdata_system.opersgroupproject_id == None:
            opersgroupproject_name = ''
        else:
            opersgroupproject_name = ormdata_system.opersgroupproject_id.ogproject_name
            
        if ormdata_system.applicationtype_id == None:
            applicationtype_name = ''
        else:
            applicationtype_name = ormdata_system.applicationtype_id.applicationtype_name

        if ormdata_system.os_id == None:
            os_name = ''
        else:
            os_name = ormdata_system.os_id.os_name + "_" + \
                ormdata_system.os_id.os_version + "_" + \
                ormdata_system.os_id.os_arch
            
        if ormdata.server_cdrom == 0:
            server_cdrom = '无'
        else:
            server_cdrom = '有'

        cpu = ormdata.cpu.all()
        cpu_num = ormdata.cpu.count()
        mem = ormdata.mem.all()
        mem_num = ormdata.mem.count()
        disk = ormdata.disk.all()
        disk_num = ormdata.disk.count()
        power = ormdata.power.all()
        power_num = ormdata.power.count()
        eth = ormdata.eth.all()
        eth_num = ormdata.eth.count()
        eth_ip = ormdata.eth_ip.all()
        eth_ip_num = ormdata.eth_ip.count()

        data = {'hardware_manufacturer':ormdata.hardware_id.hardwaremanufacturer_id.hardwaremanufacturer_name,
                'hardware_name':ormdata.hardware_id.hardware_name,
                'server_sn':ormdata.server_sn,
                'cr_name':ormdata.rackspace_id.computerroom_id.cr_name,
                'rackspace_name':ormdata.rackspace_id.rackspace_name,
                'hardware_id':ormdata.hardware_id.id,
                'server_cdrom':server_cdrom,
                'hardwarewarranty_id':ormdata.hardwarewarranty_id.hardwarewarranty_name,
                'department_name':department_name,
                'opersgroup_name':opersgroup_name,
                'opersgroupproject_name':opersgroupproject_name,
                'applicationtype_name':applicationtype_name,
                'os_name':os_name,
                'system_raid':ormdata_system.system_raid,
                'system_partition':ormdata_system.system_partition,
                'server_height':ormdata.server_height,
                'system_hostname':ormdata_system.system_hostname,
                'server_asset_tag':ormdata.server_asset_tag,
                'server_raidtype':ormdata.server_raidtype,
                'server_buydate':ormdata.server_buydate,
                'server_warranty_datetime':ormdata.server_warranty_datetime,
                'server_price':ormdata.server_price,
                'server_purchasing_director':ormdata.server_purchasing_director,
                'server_buy_datetime':ormdata.server_buy_datetime,
                'hardwarestatus':ormdata.hardwarestatus_id.hardwarestatus_name,
                'comment':ormdata.comment,
                'cpu':cpu,
                'mem':mem,     
                'disk':disk, 
                'power':power, 
                'eth':eth,
                'eth_ip':eth_ip              
                }  

        return data     


    def switch(self):
        """
        网络设备
        """
        return {}    

    def switchadd(self):
        """
        添加网络设备
        """
        return {}

    def switchedit(self):
        """
        编辑网络设备
        """
        _id = request.GET.get("id")
        ormdata = self._get_switch(_id)
        s_port = ormdata.switch_port.all()
        s_port_num = ormdata.switch_port.count()        
        sw_ip = ormdata.s_ip.all()
        sw_ip_num = ormdata.s_ip.count() 

        random_num = []
        r_num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
        #去除第一个
        for i in range(sw_ip_num-1):

            t = random.sample(r_num, 6)
            p = ""
            for i in t:
                p = p+ str(i)
            random_num.append(p)

        data = {'computerroom_id':ormdata.computerroom_id,
                'hardware_manufacturer':ormdata.hardware_id.hardwaremanufacturer_id,
                'hardware_id':ormdata.hardware_id,
                'hardwarestatus_id':ormdata.hardwarestatus_id,
                'rackspace_id':ormdata.rackspace_id,
                'sw_ip_num':sw_ip_num,
                'sw_ip':sw_ip,
                'random_num':random_num
                }

        return data

    def switchsave(self):
        """
        保存网络设备信息
        """
        _id = request.POST.get('id')
        hardware_id= request.POST.get('hardware_name')
        computerroom_id= request.POST.get('computerroom_id')
        switch_aliasname= request.POST.get('switch_aliasname')
        switch_asset_tag= request.POST.get('switch_asset_tag')   
        switch_sn= request.POST.get('switch_sn')   
        comment = request.POST.get('comment')
        sp = request.POST.getlist('sp')
        switch_ip_vlan= request.POST.get('switch_ip_vlan')
        switch_ip_addr= request.POST.get('switch_ip_addr')
        hardwarestatus_id= request.POST.get('hardwarestatus_id')
        rackspace_id= request.POST.get('rackspace_id')
        vlan_addr = []

        #vlan不能为空，ip地址允许为空
        #检查配置了vlan1和ip1，点击了添加,但是第一个没有配置
        if switch_ip_vlan != '':
            vlan_addr.append((switch_ip_vlan,switch_ip_addr))
        else:
            if len(sp) != 0:
                return json({"error":500,"msg":"配置vlan1不允许为空"})

        if len(sp) != 0 and switch_ip_vlan != '':

            for i in sp:
                v_tmp = (request.POST.get('switch_ip_vlan'+str(i)),request.POST.get('switch_ip_addr'+str(i)))
                vlan_addr.append(v_tmp)



        if _id == None:
            ormdata = self.switchmodel(hardware_id=hardware_id,
                                       computerroom_id=computerroom_id,
                                       switch_aliasname=switch_aliasname,
                                       switch_asset_tag=switch_asset_tag,
                                       switch_sn=switch_sn,
                                       hardwarestatus_id=hardwarestatus_id,
                                       rackspace_id = rackspace_id,
                                       comment=comment
                                       )
        else:
            ormdata = self._get_switch(_id)

            ormdata.hardware_id=hardware_id
            ormdata.computerroom_id=computerroom_id
            ormdata.switch_aliasname=switch_aliasname
            ormdata.switch_asset_tag=switch_asset_tag
            ormdata.switch_sn=switch_sn
            ormdata.hardwarestatus_id=hardwarestatus_id
            ormdata.rackspace_id = rackspace_id
            ormdata.comment=comment

        Begin()
        try:
            ormdata.save()


        except:
            return json({"error":500,"msg":"网络设备已经存在"})



        #添加的时候操作
        if _id == None:
            port = ormdata.hardware_id.hardware_port_num

            for i in range(1,port+1):
                s_p = self.switchportmodel(switch_port_num = i,
                                           switch_id = ormdata,
                                           switch_port_status = 0
                                           )
                s_p.save()
        else:
            #编辑操作
            self.ipaddrmodel.filter(self.ipaddrmodel.c.switch_id==_id).update(switch_id=None,ip_status=0)
            self.switchipmodel.filter(self.switchipmodel.c.switch_id.in_(_id)).remove()


        for i in vlan_addr:
            s_ip_vlan,s_ip_addr = i
            _data = self.switchipmodel(switch_ip_vlan =s_ip_vlan,
                                       switch_ip_addr = s_ip_addr.strip(),
                                       switch_id = ormdata
                                       )
            try:

                _data.save()
                
                #更新IP地址表
                #检查IP使用状态
                #IP地址不为空的情况下
                if s_ip_addr.strip() != "":
                    ip_status = list(self.ipaddrmodel.filter(self.ipaddrmodel.c.ip_address==s_ip_addr.strip()).limit(1).values(self.ipaddrmodel.c.ip_status))[0][0]
                    if ip_status == 1:
                        Rollback(close=True)
                        return json({"error":500,"msg":s_ip_addr.encode('utf8') + "已经被使用"})
                    else:
                        self.ipaddrmodel.filter(self.ipaddrmodel.c.ip_address==s_ip_addr.strip()).update(switch_id=ormdata,ip_status=1)
                        

            except:
                Rollback(close=True)
                return json({"error":500,"msg":s_ip_addr.encode('utf8') + "IP地址不存在,请先在IP池添加"})

        Commit(close=True)
        return json({"success":200,"msg":"添加成功"})


    def switchdel(self):
        """
        删除网络设备信息
        """
        _id = request.POST.get('id')

        #保存删除id
        mid = []
        #保存不允许删除id
        del_fail = []
        for i in _id.split(','):
            #检查是否包含关联
            _data = self.serverethipmodel.filter(self.serverethipmodel.c.switch_id == int(i)).count()
            if _data == 0:
                mid.append(int(i))
            else:
                del_fail.append(int(i))


        #一次删除多个
        if len(mid) != 0:
            self.switchmodel.filter(self.switchmodel.c.id.in_(mid)).remove()
            self.switchportmodel.filter(self.switchportmodel.c.switch_id.in_(mid)).remove()
            self.switchipmodel.filter(self.switchipmodel.c.switch_id.in_(mid)).remove()
            self.ipaddrmodel.filter(self.ipaddrmodel.c.switch_id.in_(mid)).update(switch_id=None,ip_status=0)

        del_fail_name = []
        if len(del_fail) != 0:
            ormdata = self.switchmodel.filter(self.switchmodel.c.id.in_(del_fail))

            for i in ormdata:
                del_fail_name.append(i.switch_aliasname)

        if len(del_fail_name) != 0:
            msg = ",".join(del_fail_name).encode('utf8') + " 包含关联数据,不允许删除"
            d = {"status":"200","msg":msg}
        else:
            d = {"status":"200","msg":"删除成功"}
        return json(d)

    def switchdetail(self):
        """
        查看网络设备明细
        """
        _id = request.GET.get("id")
        ormdata = self._get_switch(_id)
        s_port = ormdata.switch_port.all()      
        sw_ip = ormdata.s_ip.all()
        sw_ip_num = ormdata.s_ip.count()

        data = {'cr_name':ormdata.computerroom_id.cr_name,
                'hardware_manufacturer':ormdata.hardware_id.hardwaremanufacturer_id.hardwaremanufacturer_name,
                'hardware_name':ormdata.hardware_id.hardware_name,
                'switch_asset_tag':ormdata.switch_asset_tag,
                'switch_sn':ormdata.switch_sn,
                'comment':ormdata.comment,
                's_port':s_port,
                'sw_ip':sw_ip
                }

        return data
    
    def devicesmain(self):
        """
        设备机柜拓扑图主界面
        """
        return {}
    
    def devicesrackspace(self):
        """
        设备机柜拓扑图
        """
        #机房ID
        _id = request.GET.get("id")
        #functions.set_echo(True)
        orm_data = self.servermodel.filter(self.servermodel.c.rackspace_id == self.rackspacemodel.c.id
                                           ).filter(self.rackspacemodel.c.computerroom_id == _id
                                                    ).order_by(self.rackspacemodel.c.rackspace_name)
                                                    
        #orm_data = do_(select(['distinct rackspace.rackspace_name'],and_(
                                #self.servermodel.c.rackspace_id == self.rackspacemodel.c.id,
                                #self.rackspacemodel.c.computerroom_id == _id
                                #)).order_by(self.rackspacemodel.c.rackspace_name))
        
        data = {}
        for i in orm_data:
            iplist = []
            server = functions.get_object(self.servermodel, i.id, cache=True, use_local=True)
            server_ip = server.eth_ip.all()
            
            for ip in server_ip:
                iplist.append(ip.ethernet_ip)

            if i.rackspace_id.rackspace_name == "库存":
                continue
            
            if data.has_key(i.rackspace_id.rackspace_name):
    
                data[i.rackspace_id.rackspace_name].append({"server_height":i.server_height,
                                                            "server_ip":"\n".join(iplist)
                })
            else:
                data[i.rackspace_id.rackspace_name]=[]
                data[i.rackspace_id.rackspace_name].append({"server_height":i.server_height,
                                                            "server_ip":"\n".join(iplist)
                })
        return {"data":data}
    
    def exportExcel(self):
        """
        导出excel
        """
        #得到机房节点id
        _id = request.GET.get("id")
        
        import xlwt
        
        wb = xlwt.Workbook(encoding='utf8')
        styles = {'datetime': xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss'),
                  'date': xlwt.easyxf(num_format_str='yyyy-mm-dd'),
                  'time': xlwt.easyxf(num_format_str='hh:mm:ss'),
                  'header': xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00'),
                  'font':xlwt.easyxf('font: name SimSun'),
                  'default': xlwt.Style.default_style}
        
        server_title = ("机柜",
                        "品牌",
                        "型号",
                        "序列号",
                        "设备U数",
                        "资产编号",
                        "raid卡型号",
                        "保修状态",
                        "保修到期日",
                        "采购日期",
                        "采购负责人",
                        "采购价格",
                        "CPU",
                        "内存",
                        "硬盘",
                        "IP地址",
                        "主机名",
                        "操作系统",
                        "RAID",
                        "部门",
                        "运营组",
                        "运营组项目",
                        "应用主题",
                        "备注"
                        )
        
        #获取机房
        if _id == None or _id == "99999999":
            cr_data = self.computerroommodel.all()
        else:
            cr_data = self.computerroommodel.filter(self.computerroommodel.c.id == int(_id))
        
        for i in cr_data:
            
            server_data = []
            if request.user.is_superuser:
                #管理员就导出全部
                ormdata_server = self.servermodel.filter(
                    self.servermodel.c.rackspace_id==self.rackspacemodel.c.id
                                                  ).filter(self.rackspacemodel.c.computerroom_id == i.id)
                #添加excel最下的sheet
                ws = wb.add_sheet(i.cr_name,cell_overwrite_ok=True)
            else:
                #非管理员导出拥有服务器管理权的设备
                ormdata_server = self.servermodel.filter(
                                    self.servermodel.c.rackspace_id==self.rackspacemodel.c.id
                                    ).filter(self.rackspacemodel.c.computerroom_id == i.id
                                             ).filter(self.serversystemmodel.c.server_id ==self.servermodel.c.id
                                                        ).filter(
                                                        self.serversystemmodel.c.opersgroupproject_id == self.opersgroupprojectmodel.c.id
                                                                 ).filter(
                                                                     and_(
                                                                         str(request.user) + " in (opersgroupproject.ogproject_user, \
                                                                         opersgroupproject.ogproject_opuser)")
                                                                     )
                
                count = self.servermodel.filter(
                                    self.servermodel.c.rackspace_id==self.rackspacemodel.c.id
                                    ).filter(self.rackspacemodel.c.computerroom_id == i.id
                                             ).filter(self.serversystemmodel.c.server_id ==self.servermodel.c.id
                                                        ).filter(
                                                        self.serversystemmodel.c.opersgroupproject_id == self.opersgroupprojectmodel.c.id
                                                                 ).filter(
                                                                     and_(
                                                                         str(request.user) + " in (opersgroupproject.ogproject_user, \
                                                                         opersgroupproject.ogproject_opuser)")
                                                                     ).count()
                #不导出没有权限的机房名称
                if count != 0:
                    ws = wb.add_sheet(i.cr_name,cell_overwrite_ok=True)
                     
            #将所有设备的id保存到列表中
            for sid in ormdata_server:
                server_data.append(sid.id)

            for col in range(len(server_title)):
                ws.write(0,col,server_title[col],style = styles['header'])
            
            for row in range(1,len(server_data)+1):
                #从缓存中获取设备的信息
                d =  functions.get_object(self.servermodel, server_data[row-1], cache=True, use_local=True)
                d_cpu = d.cpu.all()
                cpu = []
                for c in d_cpu:
                    cpu.append(str(c.servercpu_type) + "*" +  \
                               str(c.servercpu_hz) + "*" + \
                               str(c.servercpu_num))
                    
                d_mem = d.mem.all()
                mem = []
                for m in d_mem:
                    mem.append(str(m.servermem_type) + "*" + \
                               str(m.servermem_hz) + "*" + \
                               str(m.servermem_size) + "*" + \
                               str(m.servermem_num))
                    
                d_disk = d.disk.all()
                disk = []
                for dk in d_disk:
                    disk.append(str(dk.serverdisk_type) + "*" + \
                                str(dk.serverdisk_speed) + "*" + \
                                str(dk.serverdisk_size) + "*" + \
                                str(dk.serverdisk_num))
                d_ip = d.eth_ip.all()
                ip = []
                for eip in d_ip:
                    ip.append(str(eip.ethernet_ip) + "*MIP*" + str(eip.ethernet_mip))
                    
                ormdata_system = functions.get_object(self.serversystemmodel, server_data[row-1], cache=True, use_local=True)
                
                if ormdata_system.department_id == None:
                    department_name = ''
                else:
                    department_name = ormdata_system.department_id.department_name
                    
                if ormdata_system.opersgroup_id == None:
                    opersgroup_name = ''
                else:
                    opersgroup_name = ormdata_system.opersgroup_id.opersgroup_name
        
                if ormdata_system.opersgroupproject_id == None:
                    opersgroupproject_name = ''
                else:
                    opersgroupproject_name = ormdata_system.opersgroupproject_id.ogproject_name
                    
                if ormdata_system.applicationtype_id == None:
                    applicationtype_name = ''
                else:
                    applicationtype_name = ormdata_system.applicationtype_id.applicationtype_name
        
                if ormdata_system.os_id == None:
                    os_name = ''
                else:
                    os_name = ormdata_system.os_id.os_name + "_" + \
                        ormdata_system.os_id.os_version + "_" + \
                        ormdata_system.os_id.os_arch  

                ws.write(row,0,d.rackspace_id.rackspace_name,style = styles['font'])
                ws.write(row,1,d.hardware_id.hardware_manufacturer,style = styles['default'])
                ws.write(row,2,d.hardware_id.hardware_name,style = styles['default'])
                ws.write(row,3,d.server_sn,style = styles['default'])
                ws.write(row,4,d.server_height,style = styles['default'])
                ws.write(row,5,d.server_asset_tag,style = styles['default'])
                ws.write(row,6,d.server_raidtype,style = styles['default'])
                ws.write(row,7,d.hardwarewarranty_id.hardwarewarranty_name,style = styles['default'])
                ws.write(row,8,d.server_warranty_datetime,style = styles['date'])
                ws.write(row,9,d.server_buy_datetime,style = styles['date'])
                ws.write(row,10,d.server_purchasing_director,style = styles['default'])
                ws.write(row,11,d.server_price,style = styles['default'])
                ws.write(row,12,",".join(cpu),style = styles['default'])
                ws.write(row,13,",".join(mem),style = styles['default'])
                ws.write(row,14,",".join(disk),style = styles['default'])
                ws.write(row,15,",".join(ip),style = styles['default'])
                ws.write(row,16,ormdata_system.system_hostname,style = styles['default'])
                ws.write(row,17,os_name,style = styles['default'])
                ws.write(row,18,ormdata_system.system_raid,style = styles['default'])
                ws.write(row,19,department_name,style = styles['default'])
                ws.write(row,20,opersgroup_name,style = styles['default'])
                ws.write(row,21,opersgroupproject_name,style = styles['default'])
                ws.write(row,22,applicationtype_name,style = styles['default'])
                ws.write(row,23,d.comment,style = styles['default'])
                
        ##########################################定义Content-Disposition，让浏览器能识别，弹出下载框
        fname = 'joy服务器信息列表.xls'

        browser = request.user_agent.browser

        response.headers["mimetype"]="application/ms-excel; charset=UTF-8"
        response.headers['Content-Disposition'] ='attachment; filename=%s' % fname.encode('utf-8') #解决文件名乱码/不显示的问题

        wb.save(response)
        return response        
    
    def operatingsystem(self):
        """
        操作系统信息
        """
        return {}
    def operatingsystemadd(self):
        """
        添加操作系统信息
        """
        return {}
    def operatingsystemedit(self):
        """
        编辑操作系统信息
        """
        return {}
    
    def operatingsystemsave(self):
        """
        保存操作系统信息
        """

        _id = request.POST.get('id')
        os_name= request.POST.get('os_name')
        os_version = request.POST.get('os_version')
        os_arch = request.POST.get('os_arch')

        if _id == None:
            ormdata = self.osmodel(os_name=os_name,
                                   os_version=os_version,
                                   os_arch=os_arch,
                                   )
        else:

            ormdata = functions.get_object(self.osmodel, _id, cache=True, use_local=True)
            ormdata.os_name=os_name
            ormdata.os_version=os_version
            ormdata.os_arch=os_arch

        try:
            ormdata.save()

            return json({"success":200,"msg":"添加成功"})
        except:
            return json({"error":500,"msg":"操作系统已经存在"})    
    
    def operatingsystemdel(self):
        """
        删除操作系统信息
        """
        _id = request.POST.get('id')

        mid = []
        for i in _id.split(','):
            mid.append(int(i))

        #一次删除多个
        self.osmodel.filter(self.osmodel.c.id.in_(mid)).remove()

        d = {"status":"200","msg":"删除成功"}
        return json(d) 
    
################################################################################################################

    def server_getdetail(self):
        """
        用于datagrid扩展明细,在datagrid上显示+号
        
        服务器设备明细
        """
        #得到设备ID
        _id = request.GET.get("id")
        
        ormdata_server =  functions.get_object(self.servermodel, _id, cache=True, use_local=True)
        ormdata_serversystem =  functions.get_object(self.serversystemmodel, _id, cache=True, use_local=True)
        
        #操作系统
        if ormdata_serversystem.os_id == None:
            os_name = ""
        else:
            os_name = ormdata_serversystem.os_id.os_name + "_" + \
                                ormdata_serversystem.os_id.os_version + "_" + \
                                ormdata_serversystem.os_id.os_arch
        
        #项目负责人
        if ormdata_serversystem.opersgroupproject_id == None:
            ogproject_user = ""
        else:
            ogproject_user = ormdata_serversystem.opersgroupproject_id.ogproject_user
        #运维负责人
        if ormdata_serversystem.opersgroupproject_id == None:
            ogproject_opuser = ""
        else:
            ogproject_opuser = ormdata_serversystem.opersgroupproject_id.ogproject_opuser
        
        #设备备注
        server_comment = ormdata_server.comment
        
        ipinfo = ormdata_server.eth_ip.all()
        ip = []
        for i in ipinfo:
            ip.append(i.ethernet_ip + " MIP " + i.ethernet_mip)
        
        return {"os_name":os_name,
                "ogproject_user":ogproject_user,
                "ogproject_opuser":ogproject_opuser,
                "ip":" , ".join(ip),
                "server_comment":server_comment
                }